/**
 * This file is part of magnolia-module-bespin.
 * 
 * magnolia-module-bespin is free software: you
 * can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published
 * by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 * 
 * magnolia-module-bespin is distributed in the hope that it will be
 * useful, but WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE.  See the GNU General Public
 * License for more details.
 * 
 * You should have received a copy of the GNU General
 * Public License along with magnolia-module-bespin.  If not, see
 * <http://www.gnu.org/licenses/>.
 */

package com.nrgedge.magnolia.module.bespin;

import info.magnolia.cms.beans.config.ContentRepository;
import info.magnolia.cms.core.Content;
import info.magnolia.cms.gui.control.Edit;
import info.magnolia.cms.util.NodeDataUtil;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;

/**
 * @author brian.bowman@nrg-edge.com
 * @author adam.galloway@nrg-edge.com
 */
public class BespinEdit extends Edit {

	private static final String BESPIN_SETTINGS_LOCATION = "/modules/bespin/settings";
	
	public BespinEdit() {
	}

	public BespinEdit(String name, String value) {
		super(name, value);
	}

	public BespinEdit(String name, Content websiteNode) {
		super(name, websiteNode);
	}

	public String getHtml() {
		String bespinSettings = NodeDataUtil.getString(ContentRepository.CONFIG, BESPIN_SETTINGS_LOCATION);
		String id = this.getId();
		StringBuffer html = new StringBuffer(); 
		
		if (id == null) {
			id = this.getName();
		}

		html.append("<div")
			.append(" id=\"" + id + "\"")
			.append(" style=\"display: inline-block; width: 100%; height: 480px;\"")
			.append(this.getHtmlCssClass())
			.append(this.getHtmlCssStyles())
			.append(getHtmlEvents());
		if (StringUtils.isNotEmpty(bespinSettings)) {
			html.append(" data-bespinoptions='{" + bespinSettings + "}'");
		}
		html.append("></div>")
			.append("<script type=\"text/javascript\">")
			.append("    window.onBespinLoad = function() {")

			.append("        mgnl.util.DHTMLUtil.addOnResize(function(){")
			.append("           var sizeObj = mgnlGetWindowSize();") 
			.append("           var hTab = sizeObj.h - mgnlTabTop - mgnlTabBottom - 50;")
			.append("           var bespinDiv = document.getElementById('" + id + "');")
			.append("           bespinDiv.style.height = hTab + 'px';")
			.append("        });")
			
			.append("        var bespin = document.getElementById(\"" + id + "\").bespin;")
			.append("        bespin.value = \"" + StringEscapeUtils.escapeJavaScript(getValue()) + "\";")
			.append("        bespin.setLineNumber(1);")
			.append("    };")
			.append("</script>"); //$NON-NLS-1$
		
		if (this.getSaveInfo()) {
			html.append(this.getHtmlSaveInfo());
		}
		
		return html.toString();
	}

}